package com.itheima.protocol.masterSelector;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MasterSelector {

    private final static String MASTER_PATH = "/master";

    private ZkClient zkClient;

    private IZkDataListener dataListener;
    //其他服务器
    private UserCenter server;
    //主服务器
    private UserCenter master;

    private static boolean isRunning = false;

    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);


    public MasterSelector(UserCenter server,ZkClient zkClient) {
        this.zkClient = zkClient;
        this.server = server;
        System.out.println("["+server+"]去争抢master权限");
        this.dataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

            }


            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                //如果节点被删除，重新发起选主操作
                chooseMaster();
            }
        };
    }

    //具体实现选举master逻辑
    private void chooseMaster() {
        if (!isRunning) {
            System.out.println("当前服务没有启动");
            return;
        }
        try {
            zkClient.createEphemeral(MASTER_PATH, server);
            //把server节点赋值给master
            master = server;
            System.out.println(master.getMc_name() + "-->我现在已经是master,你们要听我的");

            //定时器(模拟master释放)
            scheduledExecutorService.schedule(()->{
                System.out.println("开始释放 --->" + master.getMc_name());
                releaseMaster();
            },5, TimeUnit.SECONDS);


        } catch (ZkNodeExistsException e) {
            //master已经存在(重新获取节点数据)
            UserCenter userCenter = zkClient.readData(MASTER_PATH, true);
            if(userCenter == null){
                chooseMaster();
            }else {
                master = userCenter;
            }

        }

    }


    //释放锁
    private void releaseMaster() {
        //判断当前是否是master，只有是master才会被释放
        if(checkIsMaster()){
            zkClient.delete(MASTER_PATH);
        }
    }

    //判断是否是master
    private boolean checkIsMaster() {
        //判断当前server是否是master
        UserCenter userCenter = zkClient.readData(MASTER_PATH);
        if(userCenter.getMc_name().equals(server.getMc_name())){
            master = userCenter;
            return true;
        }
        return false;
    }

    public void start() {
        //启动服务
        if(!isRunning){
            isRunning = true;
            //注册节点事件
            zkClient.subscribeDataChanges(MASTER_PATH,dataListener);
            chooseMaster();
        }
    }

    public void stop() {
        //停止服务....
        if(isRunning){
            isRunning = false;
            scheduledExecutorService.shutdown();
            zkClient.unsubscribeDataChanges(MASTER_PATH,dataListener);
            releaseMaster();
        }
    }

}
